//
// Created by ms on 2025/10/21.
//

#include "SlideFilter.h"

#include <string.h>

SlideFilter::SlideFilter(size_t size) {
	if (size < 4) size = 4;

	buffer = new float[size];
	_size  = size;

	is_static_buffer = false;
	memset(&priv, 0, sizeof(priv));
}

SlideFilter::SlideFilter(float* buf, size_t size) {
	buffer = buf;
	_size = size;

	is_static_buffer = true;
	memset(&priv, 0, sizeof(priv));
}

SlideFilter::~SlideFilter() {
	if (!is_static_buffer) {
		delete[] buffer;
	}

	_size = 0;
}

void SlideFilter::clear() {
	memset(&priv, 0, sizeof(priv));
}

float SlideFilter::operator()(float input) {
	if (priv.count == _size) {
		priv.sum -= buffer[priv.index];
		priv.last_del = buffer[priv.index];
	}
	else {
		priv.count++;
		priv.last_del = 0;
	}

	buffer[priv.index] = input;
	priv.sum += input;
	priv.index = (priv.index + 1) % _size;

	return static_cast<float>(priv.sum / priv.count);
}
